// pages/index/collection/collection.js
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    words:'',
    collectionList:[],
    searchList:[],
    total:0,
    pageNum:1,
    pageSize:10,
    mediaType:'',
    placeholder:'请输入搜索内容'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const words = wx.getStorageSync('words')
    this.setData({words:words})
    wx.removeStorageSync('words')
    
    this.getData()
  },
  //网络请求，获取数据
  getData(){
    app.$http.get('/app/collection/list', {pageNum:this.data.pageNum,pageSize:this.data.pageSize,mediaTitle:this.data.words}).then(res =>{
      if(res.data.total == 0){
        app.$http.get('/app/collection/list', {pageNum:this.data.pageNum,pageSize:this.data.pageSize,mediaTitle:''}).then(res =>{
          this.setData({collectionList:res.data.records})
        })
      }else{
        this.setData({collectionList:res.data.records})
      }
      this.setData({words:''})
    }).catch(err => {
      console.log(err)
    })
  },
  onInput: function(e){
    if(e.detail.value != ""){
      this.setData({words:e.detail.value})
      app.$http.get('/app/collection/list', {pageNum:1,pageSize:5,mediaTitle:e.detail.value}).then(res => {
        this.setData({searchList:res.data.records})
      })
    }else{
      this.setData({searchList:[]})
    }
  },
  onBlur(){
    this.setData({
      searchList:[]
    })
  },
  //搜索
  toSearch(){
    this.setData({pageNum:1})
    this.getData()
  },
  //到集合页面
  toCollection: function(e){
    const collection = e.currentTarget.dataset.item;
    wx.setStorageSync('collection', collection)
    wx.navigateTo({
      url: '/pages/index/collection/collection',
    })
  },
  //滑动到底部
  reachBottom() {
    app.$http.get('/app/collection/list', {pageNum: this.data.pageNum + 2, pageSize: 5, mediaTitle: this.data.words}).then(res => {
      const records = res.data.records && res.data.records || [];
      if (records.length === 0) {
          wx.showToast({
              title: '没有更多数据了',
              icon: 'none',
              duration:500
          });
          return;
      }
      this.setData({
        pageNum: this.data.pageNum + 1,
        collectionList:[...this.data.collectionList,...records]
      });
    }).catch(err => {
        console.log(err);
    });
  },
})